package fu.capstone.hanoicityguide.presentation.fragment.nightlife;

import org.mapsforge.core.model.LatLong;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.overlay.Marker;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.nightlife.NightLifeBO;
import fu.capstone.hanoicityguide.business.bo.nightlife.NightLifeBOImp;
import fu.capstone.hanoicityguide.business.model.NightLife;
import fu.capstone.hanoicityguide.common.offlinemapultility.OfflineMapUtil;
import fu.capstone.hanoicityguide.common.utility.LocationSetting;

public class NightLifeOfflineMapFragment extends Fragment{

	private OfflineMapUtil util;
	private MapView mapview;
	private LatLong nightlife_geo;
	private LocationSetting locationSetting;
	private NightLifeBO nightlifeBO;
	private NightLife nightlife;
	public NightLifeOfflineMapFragment() {}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View nightlifeOfflineMapFragment = inflater.inflate(R.layout.offline_map_fragment, container, false);
		util = new OfflineMapUtil(container.getContext());
		mapview = (MapView) nightlifeOfflineMapFragment
				.findViewById(R.id.mapView);
		
		/* Get place data */
		Bundle bundle = this.getArguments();
		int nightlifeID = bundle.getInt("NightLifeID", 0);
		if (nightlifeID != 0) {

			nightlifeBO = new NightLifeBOImp(container.getContext());
			nightlife = nightlifeBO.browseNightLife(nightlifeID);
			nightlife_geo = util.convertGeoCoordinateToLatLong(nightlife
					.getGeo());
		}
		
		/* Setup map and create markers */
		locationSetting = new LocationSetting(container.getContext());
		if (locationSetting.getGPSSetting(container.getContext())) {
			util.setupofflinemap(mapview, container.getContext());
			Marker placeMarker = util.createMarker(container.getContext(),
					nightlife_geo, nightlife.getName(), nightlife.getType());
			LatLong mylocation = util.getcurrentLocation(
					container.getContext(), mapview);

			Marker mylocationMarker = util.createMyLocationMarker(container.getContext(),
					mylocation, R.drawable.mylocationmarker);

			Layers layers = this.mapview.getLayerManager().getLayers();
			layers.add(placeMarker);
			layers.add(mylocationMarker);

			try{
			/* routing */
			util.initHopper();
			util.calcPath(mylocation.latitude, mylocation.longitude,
					nightlife_geo.latitude, nightlife_geo.longitude, mapview);
			}catch(Exception e) {
				Log.v("Nightlife offline map", e.toString());
			}
		}
		else {
			locationSetting.showSettingsAlert();
		}
		
		return nightlifeOfflineMapFragment;
	}

}
